package net.begincode.common.auth;


import net.begincode.common.exception.ErrorCode;
import net.begincode.common.exception.Status;
import net.begincode.common.exception.StatusException;
import org.springframework.util.CollectionUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;

public class AuthFilter implements Filter {
    private AuthChecker authChecker;
    private List<String> excludeUrls;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void destroy() {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        if (isExcludedUri(((HttpServletRequest) servletRequest).getRequestURI(), this.excludeUrls)) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        if (!authChecker.isLogin((HttpServletRequest) servletRequest)) {
            throw new StatusException(Status.error(ErrorCode.AUTH_ERROR, "用户未登录"));
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }

    public AuthChecker getAuthChecker() {
        return authChecker;
    }

    public void setAuthChecker(AuthChecker authChecker) {
        this.authChecker = authChecker;
    }

    public List<String> getExcludeUrls() {
        return excludeUrls;
    }

    public void setExcludeUrls(List<String> excludeUrls) {
        this.excludeUrls = excludeUrls;
    }

    /**
     * 判断uri是否例外
     */
    public boolean isExcludedUri(String uri, List<String> excludeUrls) {
        if (CollectionUtils.isEmpty(excludeUrls)) {
            return false;
        }
        for (String url : excludeUrls) {
            url = url == null ? "" : url.trim();
            if (url.endsWith("*")) {
                String sub = url.substring(0, url.length() - 1);
                if (uri.startsWith(sub)) {
                    return true;
                }
            } else {
                if (uri.endsWith(url)) {
                    return true;
                }
            }
        }
        return false;
    }
}
